package com.xidian.zhiancloud.controller.accidentManage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xidian.zhiancloud.constant.AccidentManagementConstant;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.dto.accidentMessage.AccidentHandleDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.AccidentHandle;
import com.xidian.zhiancloud.model.AccidentHandleSurveyTeam;
import com.xidian.zhiancloud.model.AccidentMessage;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.accidentmessage.AccidentHandleQO;
import com.xidian.zhiancloud.service.accidentManage.AccidentHandleService;
import com.xidian.zhiancloud.service.accidentManage.AccidentHandleSurveyTeamService;
import com.xidian.zhiancloud.service.accidentManage.AccidentMessageService;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.service.user.WorkFlowUserService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.util.zyf.ExcelUtils;
import com.xidian.zhiancloud.vo.accidentmessage.AccidentHandleExportVO;
import com.xidian.zhiancloud.vo.accidentmessage.AccidentHandleVO;
import com.xidian.zhiancloud.vo.accidentmessage.AccidentMessageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName AccidentHandleController
 * @Description 事故调查处理信息管理
 * @Author zc
 **/
@RestController
@RequestMapping("/accidentHandle")
public class AccidentHandleController extends BaseController {

    @Autowired
    private AccidentHandleService accidentHandleService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private AccidentHandleSurveyTeamService accidentHandleSurveyTeamService;

    @Autowired
    private AccidentMessageService accidentMessageService;

    @Autowired
    private WorkFlowUserService workFlowUserService;
    /**
     * 添加事故调查处理信息
     * @param accidentHandleDTO 传入事故审核信息实体类
     * @return 返回是否添加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> addAccidentHandle(AccidentHandleDTO accidentHandleDTO){
        accidentHandleDTO.getAccidentHandle().setCompanyId(getSessionUserCompanyId());
        accidentHandleDTO.getAccidentHandle().setCreator(getSessionUserid());
        accidentHandleDTO.getAccidentHandle().setCreateTime(new Date(System.currentTimeMillis()));
        return ResultDTO.successOf(accidentHandleService.addAccidentHandle(accidentHandleDTO),
                GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id删除事故调查处理信息
     * @param ids 传入事故处理信息id
     * @return 返回是否删除成功
     */
    @PostMapping("/delete")
    public ResultDTO<Boolean> deleteByIds(Long[] ids){
        accidentHandleService.deleteByIds(ids);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 更新事故调查处理信息
     * @param accidentHandleDTO 传入事故处理信息
     * @return 返回是否更新成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(AccidentHandleDTO accidentHandleDTO){
        //检验当前操作人是否有权限
        List<Long> ids = workFlowUserService.getAccidentSurvey(getSessionUserCompanyId());
        Long currentUserId = getSessionUserid();
        if(!ids.contains(currentUserId)){
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        accidentHandleDTO.getAccidentHandle().setCompanyId(null);
        accidentHandleDTO.getAccidentHandle().setCreateTime(null);
        accidentHandleDTO.getAccidentHandle().setCreator(null);
        return ResultDTO.successOf(accidentHandleService.updateHandleMsgById(accidentHandleDTO),
                GeneralResponseEnums.SUCCESS);
    }

    /**
     * 条件查询
     * @param accidentHandleQO 请求参数：部门、事故类型、事故等级、处理状态、事故发生时间、关键字
     * @return 返回查询结果
     */
    @GetMapping("/getList")
    public ResultDTO<IPage<AccidentHandleVO>> getListByQO(AccidentHandleQO accidentHandleQO){
        if(accidentHandleQO.getCurrent() == null || accidentHandleQO.getSize() == null){
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }

        accidentHandleQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(accidentHandleService.getListByQO(accidentHandleQO),GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据事故id查看事故处理信息
     * @param id 已处理事故实体
     * @return 返回事故处理信息
     */
    @GetMapping("/getById")
    public ResultDTO<AccidentHandleVO> getById(@RequestParam("id") Long id){
        return ResultDTO.successOf(accidentHandleService.getById(id),GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     * @param response
     * @param ids 事故调查处理id
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response,Long[] ids) throws IOException{
        if(ids == null || ids.length==0){
            return;
        }

        List<AccidentHandle> list = accidentHandleService.listByIds(Arrays.asList(ids));
        List<AccidentHandleExportVO> new_list = new ArrayList<>();

        list.forEach(object -> {
            AccidentHandleExportVO vo = new AccidentHandleExportVO();

            BeanUtils.copyProperties(object,vo);

            AccidentMessageVO accidentMessageVO = accidentMessageService.getById(vo.getAccidentId());
            vo.setAccidentNo(accidentMessageVO.getAccidentNo());
            vo.setAccidentName(accidentMessageVO.getAccidentName());
            vo.setBriefHistory(accidentMessageVO.getBriefHistory());
            vo.setHappenTime(accidentMessageVO.getHappenTime());
            vo.setPosition(accidentMessageVO.getPosition());
            vo.setPersonSituation(accidentMessageVO.getPersonSituation());
            vo.setOnSiteTreatment(accidentMessageVO.getOnSiteTreatment());
            vo.setMeasuresTaken(accidentMessageVO.getMeasuresTaken());

            LambdaQueryWrapper<AccidentHandleSurveyTeam> query = new LambdaQueryWrapper<>();
            query.eq(AccidentHandleSurveyTeam::getAccidentHandleId,vo.getId());
            List<AccidentHandleSurveyTeam> teamList = accidentHandleSurveyTeamService.list(query);
            String reviewers = "";
            for (AccidentHandleSurveyTeam obj : teamList) {
                SysUser user = userService.getById(obj.getMemberId());
                if(user == null){
                    continue;
                }else{
                    reviewers += user.getName();
                    reviewers += ",";
                }
            }

            vo.setReviewerNames(reviewers);

            SysUser firstDuty = userService.getById(vo.getFirstDuty());
            SysUser secondDuty = userService.getById(vo.getSecondDuty());
            vo.setFirstDutyName(firstDuty==null ? "该用户不存在" : firstDuty.getName());
            vo.setSecondDutyName(secondDuty==null ? "该用户不存在" : firstDuty.getName());

            /*SysUser creator = userService.getById(accidentMessageVO.getCreator());
            vo.setCreatorName(creator == null?"该用户不存在" : creator.getName());*/

            Organization org = organizationService.getById(accidentMessageVO.getDepartmentId());
            vo.setDepartmentName(org == null ? "该部门不存在" : org.getName());

            vo.setTypeStr(AccidentManagementConstant.Type.get(vo.getType()));
            vo.setAccidentTypeStr(AccidentManagementConstant.AccidentType.get(vo.getAccidentType()));
            vo.setAccidentRankStr(AccidentManagementConstant.AccidnetRank.get(vo.getAccidentRank()));
            vo.setHandleStatusStr(AccidentManagementConstant.HandleStatus.get(accidentMessageVO.getHandleStatus()));

            new_list.add(vo);
        });

        ExcelUtils.exportExcel(new_list,"事故调查处理","事故调查处理", AccidentHandleExportVO.class,"事故调查处理",response);
    }
}
